<template>
  <px-button v-has="'ALL_RULES_ADD'" type="primary" style="margin-bottom: 8px" @click="isDrawerShow = true">新建规则</px-button>
  <px-table :data="tableData" class="equip-table" height="calc(100vh - 240px)" border>
    <px-table-column prop="alarmLevel" label="级别">
      <template #default="scope">
        <px-tag style="color: #fff" round :color="tagBgColorList[scope.row.alarmLevel]"> {{ scope.row.alarmLevel }} </px-tag>
      </template>
    </px-table-column>
    <px-table-column prop="pushPost" label="推送岗位" min-width="200" show-overflow-tooltip />
    <px-table-column prop="pushChannelName" label="推送渠道" min-width="120" show-overflow-tooltip />
    <px-table-column prop="pushTemplate" label="推送文案模板" min-width="200" show-overflow-tooltip />
    <px-table-column prop="status" label="状态">
      <template #default="scope">
        <div class="status">
          <div :class="['circle', scope.row.enableStatus === 'ON' ? 'green' : 'red']" />
          <div :style="{ color: scope.row.enableStatus === 'ON' ? '#10B981' : '#EF4444' }">
            {{ scope.row.enableStatus === "ON" ? "启用" : "停用" }}
          </div>
        </div>
      </template>
    </px-table-column>
    <px-table-column label="操作" class-name="small-padding fixed-width">
      <template #default="scope">
        <px-tooltip content="编辑" placement="top">
          <px-button v-has="'ALL_RULES_EDIT'" link type="primary" icon="EditPen" @click="handleUpdate(scope.row)" />
        </px-tooltip>
        <px-tooltip content="删除" placement="top">
          <px-button v-has="'ALL_RULES_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
        </px-tooltip>
      </template>
    </px-table-column>
  </px-table>
  <!-- <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="queryTable" /> -->

  <!--新建报警规则-->
  <px-dialog v-model="isDrawerShow" :title="rowId ? '编辑规则' : '新建规则'" width="800px" @close="handelCancel">
    <px-form ref="formRef" :model="form" label-width="120px" label-position="right" :rules="rules">
      <px-form-item label="报警级别" prop="alarmLevel">
        <px-select v-model="form.alarmLevel" style="width: 100%" placeholder="请选择报警级别">
          <px-option v-for="item in levelList" :key="item.value" :label="item.name" :value="item.name" />
        </px-select>
      </px-form-item>
      <px-form-item label="推送岗位" prop="pushPost">
        <px-select
          v-model="form.pushPost"
          style="width: 100%"
          placeholder="请选择推送岗位"
          multiple
          filterable
          collapse-tags
          collapse-tags-tooltip
          clearable
        >
          <px-option v-for="item in pushPostList" :key="item.positionId" :label="item.positionName" :value="item.positionId" />
        </px-select>
      </px-form-item>
      <px-form-item label="推送渠道" prop="pushChannel">
        <px-checkbox-group v-model="form.pushChannel" clearable>
          <px-checkbox v-for="item in channelList" :key="item.id" :label="item.value">
            {{ item.name }}
          </px-checkbox>
        </px-checkbox-group>
      </px-form-item>
      <px-form-item label="推送文案模板" prop="pushTemplate">
        <px-select v-model="form.pushTemplate" style="width: 100%" placeholder="请选择推送文案模板">
          <px-option
            v-for="item in templateList"
            :key="item.templateId"
            :label="item.templateName"
            :disabled="item.disabled"
            :value="item.templateId"
          />
        </px-select>
      </px-form-item>
      <px-form-item label="启用状态" prop="enableStatus">
        <px-radio-group v-model="form.enableStatus" style="width: 500px">
          <px-radio label="ON">启用</px-radio>
          <px-radio label="OFF">停用</px-radio>
        </px-radio-group>
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="handelCancel">取消</px-button>
        <px-button type="primary" @click="handleSubmit(formRef)"> 确定 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<script setup lang="ts">
import {
  handleRulesAddApi,
  handleRulesDeleteApi,
  handleRulesDetailApi,
  handleRulesUpdateApi,
  queryPostList,
  queryRulesListApi,
  queryTemplateListApi
} from "@/api/alert";
import { queryDictData } from "@/api/common";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from "vue";

const formRef = ref();
const { proxy }: any = getCurrentInstance();

const data = reactive<Record<string, any>>({
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  tableData: [],
  rowId: "", // 行数据id
  form: { pushPost: [] },
  isDrawerShow: false,
  levelList: [],
  pushPostList: [],
  channelList: [],
  templateList: [], // 模板列表
  rules: {
    alarmLevel: [{ required: true, message: "请选择报警级别", trigger: ["blur", "change"] }],
    pushChannel: [{ required: true, message: "请选择推送渠道", trigger: ["blur", "change"] }],
    enableStatus: [{ required: true, message: "请选择启用状态", trigger: ["blur", "change"] }],
    pushPost: [{ required: true, message: "请选择推送岗位", trigger: ["blur", "change"] }],
    pushTemplate: [{ required: true, message: "请选择推送文案模板", trigger: ["change"] }]
  }
});

const tagBgColorList = {
  一级报警: "#E02B2B",
  二级报警: "#FF771E",
  三级报警: "#F1B11A",
  四级报警: "#4A9BFF"
};

const { queryParams, tableData, form, isDrawerShow, levelList, pushPostList, channelList, templateList, rules, rowId } = toRefs(data);

// 进入页面时触发
onMounted(async () => {
  queryTable();
  getSelect();
  const templateData = await queryTemplateListApi({ pageSize: 999 });
  let data = [];
  if (templateData?.data && templateData?.data.length > 0) {
    data = templateData?.data.map(item => {
      let disabled = item.enableStatus === "OFF";
      return { ...item, disabled };
    });
  }
  templateList.value = data;
});

const getSelect = async () => {
  channelList.value = await queryDictData({ typeCode: "ALARM_PUSH_CHANNEL" });
  levelList.value = await queryDictData({ typeCode: "ALARM_LEVEL" });
  pushPostList.value = await queryPostList();
};
const queryTable = async () => {
  tableData.value = await queryRulesListApi(queryParams.value);
  //后端任务这个表数量不会超过二十条，无需分页
  // total.value = data?.total;
};

const handleDelete = async row => {
  try {
    const { id } = row;
    PxMessageBox.confirm(`是否确认删除该条报警推送规则？`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    }).then(async () => {
      await handleRulesDeleteApi({ id });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      queryTable();
    });
  } catch (error) {
    console.log(error);
  }
};

const handleUpdate = async row => {
  try {
    const { id } = row;
    rowId.value = id;
    const data = await handleRulesDetailApi({ id });
    let { pushChannel, pushPost } = data;
    try {
      pushPost = pushPost.split(",").map(element => {
        return parseInt(element);
      });
    } catch (error) {
      console.error(error);
      pushPost = [];
    }

    form.value = { ...data, pushChannel: pushChannel.split(","), pushPost: pushPost };
    isDrawerShow.value = true;
  } catch (error) {
    console.error(error);
  }
};

const handelCancel = () => {
  reset();
  isDrawerShow.value = false;
};
/** 表单重置 */
function reset() {
  form.value = {
    alarmLevel: "",
    pushPost: [],
    pushChannel: [],
    pushTemplate: "",
    enableStatus: ""
  };
  proxy.resetForm("formRef");
  rowId.value = "";
}

const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const { pushChannel, pushPost } = form.value;
      if (rowId.value) {
        //报警等级这里直接使用中文保存，后台说后续优化
        await handleRulesUpdateApi({
          alarmId: rowId.value,
          ...form.value,
          pushChannel: pushChannel.join(","), //这里存id还是value什么的待定
          pushPost: pushPost.join(",")
        });
        PxMessage.success("修改成功");
      } else {
        await handleRulesAddApi({
          ...form.value,
          pushChannel: pushChannel.join(","),
          pushPost: pushPost.join(",")
        });
        PxMessage.success("创建成功");
      }
      handelCancel();
      queryTable();
    }
  });
};
</script>

<style lang="scss" scoped>
.status {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: left;

  .circle {
    width: 6px;
    height: 6px;
    margin-right: 8px;
    border-radius: 50%;
  }

  .green {
    background-color: #10b981;
  }

  .red {
    background-color: #ef4444;
  }
}
</style>
